import { myRequest } from '@/utils/request';
import { userManager } from '@/utils/user';
import {shopItemService} from '@/services/shop_item'
import { tokenManager } from '@/utils/token';


export var creditService = {

  createCertification: (certificationData) => {
    return new Promise((resolve, reject) => {
      myRequest.request({
        url: 'credits/certifications',
        method: 'POST',
        data: certificationData,
        success: (res) => {
          resolve(res);
        },
        error: (err) => {
          reject(err);
        }
      });
    });
  },
  getCreditRecord:function(success){
        myRequest.request({
            url:'credits/records/'+userManager.getUserId(),
            method:'GET',
            data:null,
            success:success
        })
  },
  getCreditSummary:function(success){
        myRequest.request({
            url:'credits/summary/'+userManager.getUserId(),
            method:'GET',
            data:null,
            success:success
        })
  },

    addNewCredit:function(credit,courseName,method,user_id,success){
      var new_credit= shopItemService.updateCredit(credit)
      myRequest.request({
            url:'credits/records',
            method:'POST',
            data:{
                id:'0',
                userId:user_id,
                method:method,
                courseName:courseName,
                credits:new_credit,
                recordTime:new Date()
            },
            success:success
        })

  },
    getPoetryQuestion: () => {
        return new Promise((resolve, reject) => {
            myRequest.request({
                url: 'credits/new-poetry/question', // 对应后端新增的接口
                method: 'GET',
                success: (res) => {
                    resolve(res);
                },
                error: (err) => {
                    reject(err);
                }
            });
        });
    },
    submitPoetryChallenge: (poemId, userAnswers) => {
    return new Promise((resolve, reject) => {
      myRequest.request({
        url: 'credits/new-poetry/challenge',
        method: 'POST',
        data: {
          poemId: poemId,
          userAnswers: userAnswers
        },
        success: (res) => {
          resolve(res);
        },
        error: (err) => {
          console.error('creditService.submitPoetryChallenge 提交失败:', err);

          reject(err);
        }
      });
    });
    },
    /**
   * 检查学生是否已经获得了某门课程的学分 (新方法)
   * @param {string} userId - 学生用户ID
   * @param {string} courseName - 课程名称
   * @returns {Promise<boolean>} - true 表示已获得学分，false 表示未获得
   */
  checkStudentCourseCreditStatus: (userId, courseName) => {
    return new Promise((resolve, reject) => {
      myRequest.request({
        url: `credits/check-course-credit?courseName=${encodeURIComponent(courseName)}`, // 对应后端新接口
        method: 'GET',
        // headers: { // myRequest 应该已经处理了 token
        //   'Authorization': `Bearer ${tokenManager.getToken()}`
        // },
        success: (res) => {
          if (res.code === 1000 && typeof res.data === 'boolean') {
            resolve(res.data); // 返回 true 或 false
          } else {
            // 如果后端返回的格式不符合预期，也视为未认证
            console.error('checkStudentCourseCreditStatus 接口返回数据格式异常:', res);
            resolve(false); 
          }
        },
        error: (err) => {
          console.error('checkStudentCourseCreditStatus 接口调用失败:', err);
          // 接口调用失败，也视为未认证
          resolve(false); 
        }
      });
    });
  }

};

export async function createCourseCertification(courseName, imageUrl, description) {
    return new Promise((resolve, reject) => {
        myRequest.request({
            url: 'credits/certifications',
            method: 'POST',
            data: {
                courseName,
                imageUrl,
                description
            },
            success: (res) => {
                // res 即为后端返回的 Result 对象
                resolve(res);
            },
            error: (err) => {
                console.error('creditService.createCourseCertification 提交失败:', err);
                reject(err);
            }
        });
    });
}
export default creditService;